package reg.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import reg.localization.Position;

public class JDBCLocalizacionesDAO implements ILocalizacionesDAO{

	private Connection conn;
	
	public JDBCLocalizacionesDAO()
	{
		conn = ConnectionManager.getInstance().checkOut();
	}
	
	@Override
	public Position getLocalizacion(String city) {
		String sql = "SELECT * FROM Localizaciones WHERE (idCiudad = ?)";
        PreparedStatement stmt = null;
        ResultSet result = null;
        
        Position localizacionResult = null;

        try {
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, city);

            result = stmt.executeQuery();

            result.next();
            
            localizacionResult = new Position(0, 0);
            localizacionResult.latitude = result.getDouble("latitud");
            localizacionResult.longitude = result.getDouble("longitud");
            
        } catch (SQLException e) {
            System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
            try {
                if (result != null) {
                    result.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
            }
        }

        return localizacionResult;
	}
	
	public void insertLocalizacion(String idCiudad, double longitud, double latitud) {
		 PreparedStatement stmt = null;
	        String sql = "INSERT INTO Localizaciones (idCiudad, longitud, latitud) VALUES (?, ? , ?)";

	        try {
	            stmt = conn.prepareStatement(sql);

	            stmt.setString(1, idCiudad);
	            stmt.setDouble(2, longitud);
	            stmt.setDouble(3, latitud);

	            stmt.executeUpdate();

	        } catch (SQLException e) {
	            System.out.println("Message: " + e.getMessage());
	            System.out.println("SQLState: " + e.getSQLState());
	            System.out.println("ErrorCode: " + e.getErrorCode());
	        } finally {
	            try {
	                if (stmt != null) {
	                    stmt.close();
	                }
	            } catch (SQLException e) {
	            }
	        }

	}

}
